<?php
include_once __DIR__ . '/../BaseShell.php';
while (true) {
    $ticket = Lib_Redis_List::LPop("ZHONTOU_CALL_TICKET");
    if (empty($ticket)) {//话单
        sleep(5);
        continue;
    }
//    $ticket = '{"callAnswerTime":"2023-05-29 20:55:41","callHangUpTime":"2023-05-29 20:55:50","callId":"fc-f5810e3a6311245c279ba5f53afbea63","callStartTime":"2023-05-29 20:55:36","callTime":"8.620","callType":0,"callee":"18801271672","caller":"02833033202","companyId":"22085","hangupCode":"200","memberId":"","recordType":0,"workerId":"10641"}';
    $ticket = json_decode($ticket, true);
    $callHangUpTime = strtotime($ticket['callHangUpTime']);
    //给呼叫中心生成录音的时间
    if(time() - $callHangUpTime < 6) {
        sleep(time() - $callHangUpTime);
    }
    //呼叫状态
    $call_type = $ticket['callType'] == 1 ? 2 : 1;
    $callPhone =$ticket['callee'];
    $callId = $ticket['callId'];
    $file_name = '';
    //通话时间长大于5秒
    $talk_type = $ticket['callTime'] > 1 ? 1 : 2;
    if ($ticket['callTime'] > 5) {
        $file_name = downloadFile($callId);
    }
    $caseId =  Lib_Redis_Hash::hGet("CALL_" . $callId,'caseId');
    if (!empty($caseId)) {
        $case_data = Module_Mediate_Case::getInstance()->getItemById($caseId, true);
    }
    if ($ticket['workerId']) {
        $admin = Module_User_Administrator::getInstance()->getOne([],["workerId = '{$ticket['workerId']}' or workerId2 = '{$ticket['workerId']}'"], true);
    }
    //直接 用软化机拨打电话, 没有案件信息
    if(empty($case_data)){
        Func_Log::write('call_record', "empty cases", "ticket = " . json_encode($ticket));
        //拿到这个手机号全部的案件,匹配组织
        $litigant= Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['caseId'],['where'=>["telephone = '{$callPhone}'"]]);
        if (!empty($litigant) && !empty($admin)) {
            $litigant = array_column($litigant, 'caseId');
            $caseIdStr = implode(",", $litigant);
            $case_data = Module_Mediate_Case::getInstance()->getone([], ["id in ({$caseIdStr})", "mediationOrganId={$admin['mediationOrganId']}"]);
        }
        if (!empty($admin)) {
            $case_data['mediationOrganId'] = $admin['mediationOrganId'];
        }
    }

    $call_recode = [
        'callName' => !empty($case_data['litigantName']) ? $case_data['litigantName'] : '',
        'callinNumber' => $ticket['caller'],
        'callPhone' => $callPhone,
        'callType' => $call_type,
        'callTime' => strtotime($ticket['callStartTime']),
        'callEndTime' => strtotime($ticket['callHangUpTime']),
        'talkTime' => $ticket['callTime'],
        'talkType' => $talk_type,
        'callId' => $callId,
        'fileName' => $file_name,
        'caseId' => !empty($case_data['id']) ? $case_data['id'] : '',
        'workerId' => $ticket['workerId'],
        'mediatorId' => !empty($admin['id']) ? $admin['id'] : 0,
        'mediatorName' => !empty($admin['name']) ? $admin['name'] : '',
        'mediationOrganId' => !empty($case_data['mediationOrganId']) ? $case_data['mediationOrganId'] : 0,
        'addTime' => time(),
    ];
    //外呼通话，添加记录
    $record_res = Module_Mediate_CallRecord::getInstance()->singleInsert($call_recode);
    if (!$record_res) {
        Func_Log::write('call_record', "add callout record errror", "call_recode = " . json_encode($call_recode) . ' callId = ' . $callId . ' caseId = ' . $case_data['id']);
    }
    Func_Log::write('call_record', "add callout success", "call_recode = " . json_encode($call_recode) . ' callId = ' . $callId . ' caseId = ' . $case_data['id'] . ',$record_res==' . $record_res);
    //呼入添加号码
    if($call_type == 2 && !empty($case_data['id'])) {
        //判断是否存在
        $history = Module_Mediate_CaseLitigant::getInstance()->getOne(['*'],["caseId = {$case_data['id']}","telephone = {$callPhone} and isDel = 0"]);
        if (empty($history)) {
            $litigant = Module_Mediate_CaseLitigant::getInstance()->getOne(['*'],["caseId = {$case_data['id']} order by id DESC"]);
            if (!empty($litigant)) {
                $res = Module_Mediate_CaseLitigant::getInstance()->singleInsert(
                    [
                        'caseId' => $case_data['id'],
                        'litigantName' => $litigant['litigantName'],
                        'cardId' => $litigant['cardId'],
                        'telephone' => $callPhone,
                        'mobileSource' => 2,
                    ]
                );
            }
        }

    }
    //增加 判断 必须有$caseId  在生成记录
    if (!empty($case_data['id'])) {
        $case_mediate = [
            'caseId' => $case_data['id'],
            'mediatorId' => !empty($admin['id']) ? $admin['id'] : 0,
            'mediatorName' => !empty($admin['name']) ? $admin['name'] : '',
            'type' => $call_type,
            'mobile' => $callPhone,
            'fileName' => $file_name,
            'callId' => $callId,
            'addTime' => time()
        ];
        $todayContactStutus = $talk_type == 1 ? 3 : 2;
        if(in_array($case_data['todayContactStutus'],[1,2]) && $todayContactStutus != $case_data['todayContactStutus']){
            $save_case = [
                'todayContactStutus'=>$todayContactStutus,
                'updateTime'=>time()
            ];
        }
        $res = Module_Mediate_CaseMediateLog::getInstance()->insert($case_mediate,$save_case);
        if (!$res) {
            Func_Log::write('call_record', "add case mediate errror", "case_mediate = " . json_encode($case_mediate));
        }
        if(in_array($case_data['repayStatus'],['wait_repay','break_repay', 'keep_repay','finish_repay'])){
            Module_Mediate_ReturnedMoneyPlan::getInstance()->singleUpdate(['caseId'=> $case_data['id'],'todayContactStutus'=>$todayContactStutus],'caseId');
        }
    }

    //统计
    $historylong = 0;//避免循环出错
    $history = Lib_Redis_Hash::hGetAll($ticket['workerId']);
    if($call_type == 1){
        if($talk_type == 1){//呼出
            Lib_Redis_Hash::hIncrby($ticket['workerId'],'callout_on',1);
            Lib_Redis_Hash::hIncrby($ticket['workerId'],'callout_time',$ticket['callTime']);
        }else{
            Lib_Redis_Hash::hIncrby($ticket['workerId'],'callout_not',1);
        }
        $historylong = Lib_Redis_Hash::hGet($ticket['workerId'],'callin_max_long');
        if(empty($historylong) || $historylong < $ticket['callTime'] ){
            Lib_Redis_Hash::hSet($ticket['workerId'],'callin_max_long',$ticket['callTime']);
        }

    }else{
        if($talk_type == 1){//呼入
            Lib_Redis_Hash::hIncrby($ticket['workerId'],'callin_on',1);
            Lib_Redis_Hash::hIncrby($ticket['workerId'],'callin_time',$ticket['callTime']);
        }else{
            Lib_Redis_Hash::hIncrby($ticket['workerId'],'callin_not',1);
        }
        $historylong = Lib_Redis_Hash::hGet($ticket['workerId'],'callout_max_long');
        if(empty($historylong) || $historylong < $ticket['callTime'] ){
            Lib_Redis_Hash::hSet($ticket['workerId'],'callout_max_long',$ticket['callTime']);
        }
    }
    if($history){
        Lib_Redis_Hash::expireAt($ticket['workerId'], strtotime(date('Y-m-d 23:59:59')));
    }
}
function downloadFile($callId){
    //初始化文件
    $save_date = date('Y-m-d').'/';
    $savePath = LIBRARY_DIR."/../evidencefiles/callrecord/".$save_date;
    if(!file_exists($savePath)){
        if(!@mkdir($savePath,0777,true)){
            Func_Log::write('call_record', "Can not make dir",$savePath);
            return '';
        }
    }
    //录音已经下载
    if(file_exists($savePath.$callId.'.mp3')){
        return $save_date.$callId.'.mp3';
    }
    $res = Module_CallCenter_ZhonTou_RecordFile::getInstance()->getFile(['callIds'=>$callId]);
    $return = json_decode($res,true);
    if($return && isset($return['status']) && $return['status'] == false){
        $num = Lib_Redis_String::get("DOWNLOADFILE" . $callId);
        $num = $num ? $num : 1;
        if($num > 5){
            return '';
        }
        sleep($num);
        Lib_Redis_String::setex("DOWNLOADFILE" . $callId,1800,$num+1);
        return downloadFile($callId);
    }
    $fp = fopen($savePath.$callId.'.mp3', 'w');
    $result = fwrite($fp, $res);
    fclose($fp);
    if($result && file_exists($savePath.$callId.'.mp3')){
        return $save_date.$callId.'.mp3';
    }
    Func_Log::write('call_record', "downloadFile fail","callId = ".$callId ."res = ",var_export($result,1));
    $num = Lib_Redis_String::get("DOWNLOADFILE" . $callId);
    $num = $num ? $num : 1;
    sleep(2);
    if($num > 5){
        return '';
    }
    Lib_Redis_String::setex("DOWNLOADFILE" . $callId,1800,$num+1);
    return downloadFile($callId);
}
